package com.hps.shiro.controller;

import com.hps.shiro.mapper.UserMapper;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author heps
 * @date 2018/11/19
 */
@RestController
public class LoginController {

    private UserMapper userMapper;

    public LoginController(UserMapper userMapper) {
        this.userMapper = userMapper;
    }

    @GetMapping("/notLogin")
    public String notLogin() {
        return "您尚未登陆！";
    }

    @GetMapping("/notRole")
    public String notRole() {
        return "您没有权限";
    }

    @GetMapping("/logout")
    public String logout() {
        SecurityUtils.getSubject().logout();
        return "成功注销！";
    }

    @RequestMapping("/login")
    public String login(String username, String password) {
        Subject subject = SecurityUtils.getSubject();
        // 在认证提交前准备 token（令牌）
        UsernamePasswordToken token = new UsernamePasswordToken(username, password);
        // 执行认证登陆
        subject.login(token);
        // 根据权限，指定返回数据
        String role = userMapper.getRole(username);
        if ("user".equals(role)) {
            return "欢迎登陆";
        } else if ("admin".equals(role)) {
            return "欢迎来到管理员界面";
        }
        return "权限错误";
    }
}
